package com.csx.springcloud.registry.nacos.service;

import com.csx.springcloud.registry.nacos.util.URLUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author cuisongxu
 * @date 2024/12/23 周一 20:46
 */
@Service
public class NacosRegistrySampleService {

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private RestTemplate restTemplate;

    public String helloNacos() {
        List<ServiceInstance> instances = new ArrayList<>();
        ServiceInstance serviceInstance = null;
        instances = discoveryClient.getInstances("applicationB");
        if(!instances.isEmpty()) {
            serviceInstance = instances.get(0);
        }
        // 远程调用
        assert serviceInstance != null;
        String url = URLUtil.generateURL(serviceInstance, "/restTarget/get?username=zhangsan");
        String res = restTemplate.getForObject(url, String.class);
        System.out.println("hello " + res);
        return "hello " + res;
    }


}
